﻿package com.thorqq.magictimer.download;
                
import java.io.File;

import com.thorqq.magictimer.DownloadActivity;
import com.thorqq.magictimer.R;
import com.thorqq.magictimer.db.DownloadDBhelper;
import com.thorqq.magictimer.timeLoop.TimerMgr;
import com.thorqq.magictimer.util.Util;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.SparseArray;
import android.widget.RemoteViews;
                
public class DownloadSvc extends Service implements DownloadListener
{
    public static final int MSG_DOWNLOAD_INFO = 1;

    //下载完成后是否自动安装
    public static final int AUTO_INSTALL = 1;
    public static final int AUTO_INSTALL_NO = 0;
    
    private static final String SD_PATH = Util.getSDCardDir().getAbsolutePath();
                    
    private static final int THREAD_CNT = 1;
    private static final int NOTIFICATION_ID_DOWNLOAD = 9;
    
    private SparseArray<TaskInfo> mTaskList;
    private SparseArray<Downloader> mDownloaders;
    
    private Binder mBinder;
    private Handler mHandler;
    
    private Notification mNotification;
    private NotificationManager mNotificationManager;

    

    @Override
    public void onCreate() 
    {
        Util.log("DownloadSvc.onCreate");
        super.onCreate();
                
        DownloadDBhelper.getIntance(this).open();
        mDownloaders = new SparseArray<Downloader>();
        mTaskList = DownloadDBhelper.getIntance(this).getTasks();
    }
                    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) 
    {
        Util.log("DownloadSvc.onStartCommand. " + intent);
        if (intent == null)
        {
            return START_NOT_STICKY;
        }

        //创建了下载任务
        if(intent.getExtras() != null)
        {
            String urlString = intent.getExtras().getString(TimerMgr.ALARM_INTENT_DOWNLOAD_URL);
            String filename = intent.getExtras().getString(TimerMgr.ALARM_INTENT_DOWNLOAD_FILENAME);        
            int autoInstall = intent.getExtras().getInt(
                    TimerMgr.ALARM_INTENT_DOWNLOAD_AUTO_INSTALL, AUTO_INSTALL_NO);
            if(urlString != null)
            {
                addNewTask(urlString, filename, autoInstall);
            }            
        }

        return super.onStartCommand(intent, flags, startId);
    }
                    
    @Override
    public IBinder onBind(Intent intent) 
    {
        Util.log("DownloadSvc.onBind");
        if(mBinder == null)
        {
            mBinder = new MyBinder();
        }
        return mBinder;
    }
                    
    @Override
    public boolean onUnbind(Intent intent) 
    {
        Util.log("DownloadSvc.onUnbind");
        mHandler = null;
        return super.onUnbind(intent);
    }
                        
    @Override
    public void onDestroy() 
    {
        Util.log("DownloadSvc.onDestroy");
        super.onDestroy();
        
        DownloadDBhelper.getIntance(this).close();
        if(mNotificationManager != null)
        {
            mNotificationManager.cancel(NOTIFICATION_ID_DOWNLOAD);
        }
        mTaskList = null;
        mDownloaders = null;
        mBinder = null;
        mHandler = null;
    }
    
    public class MyBinder extends Binder {
        
        public void registerHandler(Handler handler) {
            mHandler = handler;
        }
                
        //新建下载
        public TaskInfo initDownloader(String url, String path)
        {
            return createDownloader(url, path, AUTO_INSTALL_NO);
        }
        
        public TaskInfo initDownloaderAndInstall(String url, String path, boolean autoInstall)
        {
            return createDownloader(url, path, autoInstall == true ? AUTO_INSTALL : AUTO_INSTALL_NO);
        }
        
        public TaskInfo initDownloader(int taskid)
        {
            return createDownloader(taskid);
        }
        
        //获取所有下载任务
        public SparseArray<TaskInfo> getAllTask()
        {
            return mTaskList;
        }
        
        //判断某个任务是否正在下载
        public boolean isDownloading(int taskid)
        {
            Downloader downloader = mDownloaders.get(taskid);
            if(downloader != null)
            {
                return downloader.isDownloading();
            }
            else
            {
                return false;
            }
        }
        
        public boolean isDownloading()
        {
            for(int i = 0; i < mTaskList.size(); i++)
            {
                TaskInfo task = mTaskList.valueAt(i);
                if(isDownloading(task.getTaskid()))
                {
                    return true;
                }
            }
            
            return false;
        }
        
        public boolean isToPause(int taskid)
        {
            Downloader downloader = mDownloaders.get(taskid);
            if(downloader != null)
            {
                return downloader.isToPause();
            }
            else
            {
                return false;
            }            
        }
        
        public boolean isToStart(int taskid)
        {
            Downloader downloader = mDownloaders.get(taskid);
            if(downloader != null)
            {
                return downloader.isToStart();
            }
            else
            {
                return false;
            }            
        }
        
        //启动或者停止一个任务
        public void startOrStop(int taskid)
        {
            startOrStopTask(taskid);
        }

        //重新开始下载
        public void restart(int taskid)
        {
            mTaskList.get(taskid).setComplete(0);
            DownloadDBhelper.getIntance().updateTaskInfo(taskid, mTaskList.get(taskid).getFileSize(), 0);
            
            startOrStopTask(taskid);        
        }
        
        //删除一个任务。如果正在下载，则要先停止，然后再删除
        public void delete(int taskid)
        {
            Downloader downloader = mDownloaders.get(taskid);
            if(downloader != null && downloader.isDownloading())
            {
                downloader.delete();
            }
            else
            {
                mDownloaders.remove(taskid);
                mTaskList.remove(taskid);
                DownloadDBhelper.getIntance().deleteTaskInfo(taskid);
                DownloadDBhelper.getIntance().deleteThreadInfo(taskid);

                sendMessage();
            }
            
       }

    }
    
    //新建下载任务
    private void addNewTask(String url, String filename, int autoInstall)
    {
        String localfile = null;
        if(filename == null)
        {
            localfile = SD_PATH + "/" + url.substring(url.lastIndexOf("/") + 1);
        }
        else
        {
            localfile = SD_PATH + "/" + filename;
        }
        
        //判断文件是否已经存在
        File file = new File(localfile);
        if (file.exists())
        {
            for(int i = 1; i < 100000; i++)
            {                    
                File newfile = new File(SD_PATH + "/"+ "("+ i +")" + file.getName());
                if (!newfile.exists())
                {
                    file = newfile;
                    break;
                }
            }
        }

        Util.log("Download '" + file.getAbsolutePath() + "' from " + url);
        TaskInfo task = createDownloader(url, file.getAbsolutePath(), autoInstall);

        startOrStopTask(task);        
    }
    
    //启停下载任务
    private void startOrStopTask(TaskInfo info)
    {
        startOrStopTask(info.getTaskid());
    }
    
    //启停下载任务
    private void startOrStopTask(int taskid)
    {
        Downloader downloader = mDownloaders.get(taskid);
        if(downloader == null)
        {
            return;
        }
        
        if(downloader.isDownloading())
        {
            downloader.pause();
        }
        else
        {
            downloader.start();
        }
    }
        
    //更新实时下载信息
    @Override
    public void OnDownloadInfoUpdate(int taskid)
    {
        TaskInfo task = mTaskList.get(taskid);
        if(task != null && task.getState() == Downloader.DL_STATE_DELETE)
        {
            mTaskList.remove(taskid);
            DownloadDBhelper.getIntance().deleteTaskInfo(taskid);
            mDownloaders.remove(taskid);            
        }

        showNotification(task);
        sendMessage();     
        
        if(task != null 
                && task.getState() == Downloader.DL_STATE_COMPLETED
                && task.getAutoInstall() == DownloadSvc.AUTO_INSTALL)
        {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse("file://" + task.getLocalFile()), "application/vnd.android.package-archive");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(i);
        }

    }
    
    private void sendMessage()
    {
        if(mHandler != null)
        {            
            Message message = Message.obtain();
            message.what = MSG_DOWNLOAD_INFO;
            mHandler.sendMessage(message);
        }
    }
    
    //获取一个任务信息
    private TaskInfo createDownloader(int taskid)
    {
        TaskInfo task = mTaskList.get(taskid);   
        if(task == null)
        {
            return null;
        }
        
        Downloader downloader = mDownloaders.get(taskid);
        if(downloader == null)
        {
            downloader = new Downloader(this, task, THREAD_CNT, DownloadDBhelper.getIntance());
            downloader.setDownloadListener(this);
            mDownloaders.put(task.getTaskid(), downloader);
        }
        
        return task;
        
    }
    
    //根据网址和保存路径新建下载任务
    private TaskInfo createDownloader(String urlstr, String localfile, int autoInstall)
    {
        TaskInfo task = new TaskInfo(urlstr, localfile, autoInstall);
        DownloadDBhelper.getIntance().insertTaskInfo(task);
        mTaskList.put(task.getTaskid(), task);
        Downloader downloader = new Downloader(this, task, THREAD_CNT, DownloadDBhelper.getIntance());
        downloader.setDownloadListener(this);
        mDownloaders.put(task.getTaskid(), downloader);
        
        return task;
        
    }
    
    //初始化通知栏信息
    private void initNotification(TaskInfo task)
    {
        Intent notify = new Intent(this, DownloadActivity.class);
        PendingIntent pendingNotify = PendingIntent.getActivity(this,1, notify, 0);

        mNotification = new Notification();
        
        mNotification.contentView= new RemoteViews(this.getPackageName(),R.layout.download_notification);
        mNotification.icon = android.R.drawable.stat_sys_download;
        mNotification.tickerText = task.getLocalFile().substring(task.getLocalFile().lastIndexOf("/") + 1);
        mNotification.contentIntent = pendingNotify;        
        mNotification.contentView.setTextViewText(R.id.tvDownloadTitle, getString(R.string.app_name));
        mNotification.contentView.setTextViewText(R.id.tvDownloadRemark, "没有下载任务");
        
        mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(NOTIFICATION_ID_DOWNLOAD, mNotification);

    }
        
    //更新通知栏信息
    private void showNotification(TaskInfo task)
    {
        if(mNotification == null || mNotificationManager == null)
        {
            initNotification(task);
        }
        else
        {
            int downloadingCnt = 0;
            int pauseCnt = 0;
            
            int total = mTaskList.size();
            for(int i = 0; i < total; i++)
            {
                TaskInfo info = mTaskList.valueAt(i);
                if(info.getComplete() < info.getFileSize())
                {
                    //正在下载
                    if(info.getState() == Downloader.DL_STATE_DOWNLOADING)
                    {
                        downloadingCnt++;
                    }
                    //暂停下载
                    else
                    {
                        pauseCnt++;
                    }
                }
            }
            
            //下载任务：进行中x个，已暂停y个
            StringBuffer buf = new StringBuffer();
            if(downloadingCnt > 0 && pauseCnt > 0)
            {
                buf.append("下载任务：");
                buf.append(downloadingCnt).append("个").append("下载中，");
                buf.append(pauseCnt).append("个").append("已暂停");
            }
            else if(downloadingCnt == 0 && pauseCnt > 0)
            {
                buf.append("下载任务：");
                buf.append(pauseCnt).append("个").append("已暂停");
            }
            else if(downloadingCnt > 0 && pauseCnt == 0)
            {
                buf.append("下载任务：");
                buf.append(downloadingCnt).append("个").append("下载中");
            }
            else if(downloadingCnt == 0 && pauseCnt == 0)
            {
                buf.append("没有下载任务");
                mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
            }
            mNotification.contentView.setTextViewText(R.id.tvDownloadRemark, buf.toString());
            
            //下载状态图标
            if(downloadingCnt > 0)
            {
                mNotification.icon = android.R.drawable.stat_sys_download;
                //这里不会显示动画！！
                mNotification.contentView.setImageViewResource(R.id.ivDownloadImage, 
                        android.R.drawable.stat_sys_download);
            }
            else
            {
                mNotification.icon = android.R.drawable.stat_sys_download_done;
                mNotification.contentView.setImageViewResource(R.id.ivDownloadImage, 
                        android.R.drawable.stat_sys_download_done);
            }
            
            mNotificationManager.notify(NOTIFICATION_ID_DOWNLOAD, mNotification);
        }
    }

}